import { ref } from 'vue';
import { message } from 'ant-design-vue';
import api from "@/utils/api";

// 定义接口
export interface Department {
    id: number;
    nameCn: string;
    nameEn: string;
    desc: string;
    createDate: string;
    updateDate: string;
    createUser: string;
    updateUser: string;
}

// 定义响应式变量
export const departmentList = ref<Department[]>([]);
export const fetching = ref(false);
export const selectedDepartment = ref<any>(undefined);
export const selectedDept = ref<any>(null);
const newDeptName=ref();

// 部门搜索方法
export const onDepartmentSearch = async (keyword: string) => {
    await fetchDepartments(keyword);
};

// 获取部门列表
export const fetchDepartments = async (keyword: string = '') => {
    try {
        fetching.value = true;
        newDeptName.value=undefined;
        const response = await api.get('/department', {
            params: { nameCn: keyword }
        });
        departmentList.value = response.data;
        newDeptName.value=keyword;
    } catch (error) {
        message.error('获取部门列表失败');
        console.error('获取部门列表失败:', error);
    } finally {
        fetching.value = false;
    }
};

// 部门选择变化
export const onDepartmentChange = (value: any) => {
    selectedDept.value = departmentList.value.find(department =>
        (department.id) === value
    );
    if(selectedDept.value){
        newDeptName.value=undefined
    }
    // 清空相关数据
    return {
        departmentCleared: true
    };
};

export const onDepartmentBlur = () => {
    // 检查当前输入的角色是否是新角色
    if(newDeptName.value){
        selectedDepartment.value=newDeptName.value
    }
}

// 重置部门数据
export const resetDepartmentData = () => {
    selectedDepartment.value = undefined;
    selectedDept.value = null;
    departmentList.value = [];
};

// 导出所有方法
export default {
    departmentList,
    fetching,
    selectedDepartment,
    selectedDept,
    onDepartmentSearch,
    fetchDepartments,
    onDepartmentChange,
    onDepartmentBlur,
    resetDepartmentData
};